package com.zhsj.OkeHomeConsumption.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.hjq.base.BaseDialog;
import com.hjq.dialog.WaitDialog;
import com.hjq.widget.SettingBar;
import com.hjq.widget.SwitchButton;
import com.orhanobut.hawk.Hawk;
import com.zhsj.OkeHomeConsumption.R;
import com.zhsj.OkeHomeConsumption.common.Constants;
import com.zhsj.OkeHomeConsumption.common.MyActivity;
import com.zhsj.OkeHomeConsumption.common.MyApplication;
import com.zhsj.OkeHomeConsumption.common.OkeHomeConsumptionApi;
import com.zhsj.OkeHomeConsumption.empty.FormalUserInfo;
import com.zhsj.OkeHomeConsumption.event.LoginOutEvent;
import com.zhsj.OkeHomeConsumption.event.LoginUserpanterEvent;
import com.zhsj.OkeHomeConsumption.helper.ActivityStackManager;
import com.zhsj.OkeHomeConsumption.network.HttpClient;
import com.zhsj.OkeHomeConsumption.network.JsonResponseHandler;
import com.zhsj.OkeHomeConsumption.other.TimeOutHandler;
import com.zhsj.OkeHomeConsumption.other.URLEntity;
import com.zhsj.OkeHomeConsumption.ui.fragment.minehome.VersionMessageActivity;
import com.zhsj.OkeHomeConsumption.ui.fragment.minehome.VersionUpdataActivity;
import com.zhsj.OkeHomeConsumption.utils.SharedPreferanceUtils;
import com.zhsj.OkeHomeConsumption.utils.SignUtil;
import com.zhsj.OkeHomeConsumption.utils.UpdateAppUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.zhsj.OkeHomeConsumption.common.Constants.SHARED_PERFERENCE_USERINFO;

/**
 * author : Xingdx
 * <p>
 * time   : 2019/03/01
 * desc   : 设置界面
 */
public final class SettingActivity extends MyActivity
        implements SwitchButton.OnCheckedChangeListener {
    @BindView(R.id.sb_setting_agreement)
    SettingBar sbSettingAgreement;
    @BindView(R.id.sb_setting_about)
    SettingBar sbSettingAbout;
    @BindView(R.id.sb_setting_exit)
    SettingBar sbSettingExit;
    @BindView(R.id.sb_setting_xieyi)
    SettingBar sbSettingXieyi;
    @BindView(R.id.sb_setting_yinsi)
    SettingBar sbSettingYinsi;


    private SharedPreferanceUtils mSharePreferanceUtils = null;
    private BaseDialog pDialogUtils = null;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_setting;
    }

    @Override
    protected int getTitleId() {
        return R.id.tb_setting_title;
    }

    @Override
    protected void initView() {
        // 设置切换按钮的监听
    }

    @Override
    protected void initData() {
        mSharePreferanceUtils = new SharedPreferanceUtils(getActivity());
        sbSettingAgreement.setRightText(UpdateAppUtils.getAPPLocalVersionName(MyApplication.getContext()));
        pDialogUtils = new BaseDialog(this);
        if (mSharePreferanceUtils.getlifeType()==0){
            sbSettingYinsi.setVisibility(View.VISIBLE);
        }
        else {
            sbSettingYinsi.setVisibility(View.GONE);
        }
    }

    @OnClick({R.id.sb_setting_agreement, R.id.sb_setting_about,
            R.id.sb_setting_exit,R.id.sb_setting_yinsi,R.id.sb_setting_xieyi})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sb_setting_agreement:
                //版本信息
                startActivity(VersionMessageActivity.class);
                break;
            case R.id.sb_setting_about:
                startActivity(AboutActivity.class);
                break;
            case R.id.sb_setting_exit: // 退出登录
                LogoutThread();
                break;
            case R.id.sb_setting_xieyi://协议
                if (mSharePreferanceUtils.getlifeType()==0) {
                    Intent intent1 = new Intent(getActivity(), WebActivity.class).putExtra("url", OkeHomeConsumptionApi.ELVDOU_BASEURL_H5_LIFE + "app/h5/contract/2.html");
                    startActivity(intent1);
                }else if (mSharePreferanceUtils.getlifeType()==1){
                    Intent intent1 = new Intent(getActivity(), WebActivity.class).putExtra("url", OkeHomeConsumptionApi.ELVDOU_BASEURL_H5_LIFE + "app/h5/contract/3.html");
                    startActivity(intent1);
                }else {
                    Intent intent1 = new Intent(getActivity(), WebActivity.class).putExtra("url", OkeHomeConsumptionApi.ELVDOU_BASEURL_H5_LIFE + "app/h5/contract/6.html");
                    startActivity(intent1);
                }
                break;
            case R.id.sb_setting_yinsi://隐私
                Intent intent2 = new Intent(getActivity(), WebActivity.class).putExtra("url", OkeHomeConsumptionApi.ELVDOU_BASEURL_H5_LIFE + "app/h5/contract/1.html");
                startActivity(intent2);
                break;
            default:
                break;
        }
    }

    /**
     * {@link SwitchButton.OnCheckedChangeListener}
     */

    @Override
    public void onCheckedChanged(SwitchButton button, boolean isChecked) {
        toast(isChecked);
    }

    /**
     * @param
     * @return void    返回类型
     * @throws
     * @Title: LogoutThread
     * @Description: TODO
     */
    public void LogoutThread() {
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        // 生成sign值所使用的HashMap
        final HashMap<String, String> mLogoutMap = new HashMap<String, String>();
        Constants.TIME = URLEntity.getInstance().getT();
        mLogoutMap.put("v", Constants.APPVERSION);
        mLogoutMap.put("t", Constants.TIME);
        Log.e("sign time =", Constants.TIME);
        mLogoutMap.put("deviceId", URLEntity.getInstance().getImei());
        mLogoutMap.put("client", Constants.CLIENT);
        mLogoutMap.put("platform", Constants.PLAFORM);
        mLogoutMap.put("deviceToken", Constants.DEVICETOKEN);
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mLogoutMap);
        Log.e("LogoutThread sign = ", Constants.SIGN);
        // 网络计时器及线程
        // 网络计时器及线程
        TimeOutHandler.pDialogUtils = new WaitDialog.Builder(this)
                .setMessage("加载中...") // 消息文本可以不用填写
                .show();
        HttpClient.post(OkeHomeConsumptionApi.ELVDOU_LOGOUT, paramMaps, new JsonResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                TimeOutHandler.pDialogUtils .dismiss();
                pDialogUtils = null;
                try {
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("message");
                    if (code.equals("N000000")) {
                        // 数据对接正常T
                        //TODO
//                        Hawk.put(Constants.SHARED_PERFERENCE_USERINFO, null);
                        Hawk.delete(Constants.SHARED_PERFERENCE_USERINFO);
                        mSharePreferanceUtils.setToken("");
                        mSharePreferanceUtils.setIsLogin("");
                        mSharePreferanceUtils.setSaveUserInfo(null);
                        EventBus.getDefault().post(new LoginUserpanterEvent(0));
                        sbSettingExit.setVisibility(View.GONE);
                        mSharePreferanceUtils.setlifeType(0);
                        EventBus.getDefault().post(new LoginOutEvent(1));
                        finish();
//                        startActivityFinish(LoginActivity.class);
                        // 进行内存优化，销毁掉所有的界面
//                        ActivityStackManager.getInstance().finishAllActivities(LoginActivity.class);

                    } else {
                        // 数据对接失败
                        pDialogUtils.dismiss();
                        pDialogUtils = null;
                    }
                } catch (Exception ex) {
                    Log.e("LogoutThread", "token获取异常 ");
                }
            }

            @Override
            public void onFailure(Throwable e) {
                // TODO Auto-generated method stub
                super.onFailure(e);
                pDialogUtils.dismiss();
                pDialogUtils = null;
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}